#include "encode_decode.h"
#include "common.h"

/**
 * check for all ASSIGNED vars in the given list,
 * return the encode unsigned*[]
 * 
 * remember
 */
unsigned* encode_variables(variable* vars, int num_var, int num_assigned){
    //safe check
    for(int i = 0; i < num_var; i++){
        assert(vars[i].name > 0);
    }
    
    int curnum = 0;
    unsigned* encoded = malloc(sizeof(unsigned) * num_assigned);
    for(int i = 0; i < num_var; i++){
        if(vars[i].assigned){
            encoded[curnum++] = (vars[i].name<<1) | (vars[i].value ? 1 : 0);
        }
    }
    assert(curnum == num_assigned);

    return encoded;
}

/**
 * translate from unsigned* encoded to var_set
 */
variable* decode_variables(unsigned* encoded, int enc_len){
    int curnum = 0;
    variable* vars = malloc(sizeof(variable) * enc_len);

    for  (int i=0; i < enc_len; i++){
        int name = encoded[i]>>1;
        int value = encoded[i] | 0x1;
        vars[i].name = name;
        vars[i].assigned = 1;
        vars[i].value = value;
    }

    return vars;
}